package com.sharemarking.application.common.controller;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.sharemarking.application.common.entity.Menu;
import com.sharemarking.application.common.entity.Permission;
import com.sharemarking.application.common.entity.Role;
import com.sharemarking.application.common.repository.RoleRepo;
import com.sharemarking.application.common.service.MenuService;

@Controller
@RequestMapping("role")
public class RoleController {
	@Autowired
	private RoleRepo dao;
	@Autowired
	private MenuService ms;
	
	@RequestMapping(value="index",method=RequestMethod.GET)
	@PreAuthorize("hasPermission('sys:role',1)")
	public void index(Role e,Model model){
		List<Role> p=dao.findAll(new Specification<Role>() {
			@Override
			public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates=new ArrayList<Predicate>();
				predicates.add(cb.notEqual(root.get("ename").as(String.class), "ADMINISTRATOR"));
				if(!StringUtils.isEmpty(e.getName()))predicates.add(cb.like(root.get("name").as(String.class), "%"+e.getName()+"%"));
				return cb.and(predicates.toArray(new Predicate[0]));
			}
		});
		model.addAttribute("list", p);
		model.addAttribute("search", e);
	}
	
	/**
	 * 获取实体接口
	 * @param e
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.GET)
	@PreAuthorize("hasPermission('sys:role',1)")
	public String get(Role obj,Model model){
		if(obj.getId()!=0) obj=dao.findOne(obj.getId());
		List<Menu> menuList=ms.getAllMenus();
		List<Permission> permissions=new ArrayList<Permission>(menuList.size());
		for(Menu menu:menuList){
			boolean menuFound=false;
			if(obj.getPermissions()!=null)for(Permission permission:obj.getPermissions()){
				if(permission.getMenu().equals(menu)){
					permissions.add(permission);
					menuFound=true;
				}
			}
			if(!menuFound){
				Permission permission=new Permission();
				permission.setMenu(menu);
				permissions.add(permission);
			}
		}
		obj.setPermissions(permissions);
		model.addAttribute("obj",obj);
		return "role/form";
	}
	/**
	 * id==0  =>  新增实体
	 * id!=0  =>  更新实体
	 * @param e
	 * @return
	 */
	@RequestMapping(value="{id}",method=RequestMethod.POST)
	@Transactional
	@PreAuthorize("hasPermission('sys:role',#target.id==0?8:4)")
	public String post(Role target,Model model){
		if(target.getUsable()==null)target.setUsable(false);
		if(target.getId()==0){
			target.getPermissions().forEach(s->{
				s.setRole(target);
			});
			dao.save(target);
			return "redirect:index";
		}else {
			Role e=dao.findOne(target.getId());
			if(e==null)return null;
			e.setName(target.getName());
			e.setEname(target.getEname());
			List<Permission> permissions=e.getPermissions();
			for(Permission p:permissions){
				for(Permission p2:target.getPermissions()){
					if(p.equals(p2)){
						System.out.println(p2.getPermission());
						p.setPermission(p2.getPermission());
					}
				}
			}
			return "redirect:index";
		}
	}
	/**
	 * 逻辑删除
	 * @param id
	 */
	@RequestMapping(value="{id}/delete",method=RequestMethod.GET)
	@Transactional
	@PreAuthorize("hasPermission('sys:role',16)")
	public String delete(@PathVariable("id")Integer id){
		dao.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}
}
